package com.xyw.code.controller;


import com.xyw.code.constant.CommonStatusEnum;
import com.xyw.code.dto.MenuDTO;
import com.xyw.code.entity.SysMenu;
import com.xyw.code.log.SysLog;
import com.xyw.code.security.XUser;
import com.xyw.code.security.util.SecurityUtil;
import com.xyw.code.service.ISysMenuService;
import com.xyw.code.utils.Result;
import com.xyw.code.utils.XUtil;
import com.xyw.code.vo.MenuVo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 菜单权限表 前端控制器
 * </p>
 *
 * @author xuyiwei
 * @since 2019-07-30
 */
@Api(value="菜单模块")
@RestController
@RequestMapping("/menu")
public class SysMenuController {

    @Autowired
    private ISysMenuService menuService;

    /**
     * 获取路由
     *
     * @return
     */
    @GetMapping("/getRouters")
    public Result<List<MenuVo>> getRouters() {
        XUser securityUser = SecurityUtil.getUser();
        //根据用户得到用户所拥有的角色 根据角色拥有该角色所有的菜单
        return Result.ok(XUtil.buildVueMenu(menuService.selectMenuTree(securityUser.getUserId())));
    }


    /**
     * 获取所有菜单
     *
     * @return
     */
    @GetMapping("/getMenus")
    public Result getMenus() {
        return Result.ok(menuService.selectMenuTree(0));
    }

    /**
     * 获取菜单树
     *
     * @return
     */
    @GetMapping("/list")
    public Result<SysMenu> getMenuTreeList(@RequestParam(required = false) String name) {
        return Result.ok(menuService.getMenuTreeList(name));
    }

    /**
     * 添加菜单
     *
     * @param menu
     * @return
     */
    @SysLog(descrption = "新增菜单")
    @PreAuthorize("hasAuthority('sys:menu:add')")
    @PostMapping("/add")
    public Result add(@RequestBody SysMenu menu) {
        return Result.ok(menuService.save(menu));
    }

    /**
     * 修改菜单
     *
     * @param menuDto
     * @return
     */
    @SysLog(descrption = "更新菜单")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    @PostMapping("/update")
    public Result update(@RequestBody MenuDTO menuDto) {
        return Result.ok(menuService.updateMenuById(menuDto));
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @SysLog(descrption = "删除菜单")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.ok(menuService.deleteMenu(id));
    }
}

